package search;

import java.util.ArrayList;

public class BinarySearch {// 二分查找

    public static void main(String[] args) {
        int[] arr = {1, 1, 1, 1, 8, 10, 89, 100, 100, 100, 100, 12345};
        ArrayList<Integer> arrayList = binarySearch2(arr, 0, arr.length, 1);
        System.out.println(arrayList.toString());
    }

    public static int binarySearch(int[] arr, int left, int right, int findInt) {

        if (left > right) { //没有找到
            return -1;
        }
        int mid = (left + right) / 2;

        int midNum = arr[mid];
        if (findInt > midNum) { //向右递归
            return binarySearch(arr, mid + 1, right, findInt);
        } else if (findInt < midNum) {//向左递归
            return binarySearch(arr, left, mid - 1, findInt);
        } else {
            return mid;
        }
    }

    public static ArrayList<Integer> binarySearch2(int[] arr, int left, int right, int findInt) {

        if (left > right) { //没有找到
            return new ArrayList<Integer>();
        }
        int mid = (left + right) / 2;
        int midNum = arr[mid];
        if (findInt > midNum) { //向右递归
            return binarySearch2(arr, mid + 1, right, findInt);
        } else if (findInt < midNum) {//向左递归
            return binarySearch2(arr, left, mid - 1, findInt);
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            int temp = mid - 1;
            while (true) { //向左扫描
                if (arr[temp] != findInt || temp <= 0) {
                    if (temp == 0 && arr[temp] == findInt) {
                        arrayList.add(0);
                    }
                    break;
                }

                arrayList.add(temp);
                temp -= 1;
            }
            temp = mid + 1;
            while (true) {//向右扫描
                if (arr[temp] != findInt || temp > right) {
                    break;
                }
                arrayList.add(temp);
                temp += 1;
            }
            arrayList.add(mid);
            return arrayList;
        }
    }


}
